<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/21
 * Time: 13:37
 */

namespace Modules\Shop\Service;
use HiCommon\Repository\CancelReasonRepository;
use HiCommon\Repository\RoadRescueConfigRepository;
use HiCommon\Repository\RoadRescueConfigExtendRepository;
use HiCommon\Repository\RoadRescueOrderRepository;
use HiCommon\Repository\ShopRepository;

class RoadRescueService
{

    /**
     *  设置道路救援的类型列表
     *  hinq 2020 04 21
     *
     **/
    public function type_list(){
        $arr_list = [
            1 => '抢修',
            2 => '换补胎',
            3 => '开锁',
            4 => '拖车牵引',
            5 => '送油',
            6 => '接电',
            7 => '救援',
        ];
        return $arr_list;
    }

    /**
     *  获取当前机构下设置的信息
     *  hinq 2020 4 22
     *
     **/
    public function get_list( array $arr_input ){
        try{
            $arr_option['where'] = ['repairstore_id' => shop_shop_id() ];
            $arr_option['field'] = ['id', 'type' ,'pid','price'];
            $arr_option['with'] = ['extend'];
            $arr_list = RoadRescueConfigRepository::get_list( (array) $arr_input , (array) $arr_option );
            $arr_input['type_list'] = self::type_list();
            $arr_list->appends($arr_input);//添加链接参数
            $arr_list = list_page_data($arr_list, $arr_input);
            return hello_success('成功', $arr_list);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  添加道路救援的数据
     *  hinq 2020 4 21
     *
     **/
    public function store( array $arr_input ){
        try{
            \DB::beginTransaction();
            //验证数据有效性
            $temp = self::check_data( (array) $arr_input );
            if( $temp['state'] == 1 ){
                return $temp;
            }
            $shop_id = shop_shop_id();

            //获取商户信息
            $shop_info = ShopRepository::get_one_by_where( ['id'=>$shop_id] );
            if( empty( $shop_info ->first() ) ){
                return hello_error('添加失败');
            }
            $shop_info = $shop_info->toarray();
            //当前服务机构没有晚上基本信息  所在省市区  和经纬度设置
            if( $shop_info['province'] == 0 ||  empty( $shop_info['longitude'] ) || empty( $shop_info['longitude'] ) ){
                return hello_error('请先完善机构信息');
            }
            $res = true;
            $res2 = true;
            $data['repairstore_id'] = $shop_id;
            $data['pid'] = $arr_input['pid'];           //服务类型
            //当前商户下是否设置了当前服务类型
            $count = RoadRescueConfigRepository::get_count_by_where( (array) $data );
            if( $count >= 1 ){ //同一服务类型只能设置一次
                return hello_error('当前服务类型已设置');
            }
            $data['type'] = $arr_input['type'];         //收费类型   1: 按次数收费   2：按公里数收费
            if( $arr_input['type'] == 1 ){
                $data['price'] = $arr_input['price'];
            }
            $res = RoadRescueConfigRepository::add_one( (array) $data );
            $temp_extend['link_id'] = $res->id;
            if( $arr_input['type'] == 2 ) {
                foreach ($arr_input['startkm'] as $key => $vo) {
                    $temp_extend['startkm'] = $vo;    //起始公里数
                    $temp_extend['overkm'] = $arr_input['overkm'][$key];   //结束公里数
                    $temp_extend['price'] = $arr_input['pricekm'][$key];    //收费价格
                    $res = RoadRescueConfigExtendRepository::add_one((array)$temp_extend);
                }
            }
            if( $res && $res2 ){
                \DB::commit();
            }
            return hello_success('设置成功', $res);
        }catch (\Exception $exception){
            \DB::rollBack();
            return hello_error($exception->getMessage());
        }
    }

    /**
     *  验证提交过来的数据
     *  hinq 2020 4 21
     **/
    public function check_data( array $arr_input ){

        if( empty( $arr_input['pid']) ){
            return hello_error('请选择服务类型');
        }
        if( empty( $arr_input['type'] ) ){
            return hello_error('请选择收费类型');
        }
        if( $arr_input['type'] == 1 ){
             if( empty( $arr_input['price']) ){
                 return hello_error('请设置价格');
             }
        }else if( $arr_input['type'] == 2 ){
            if( empty( hi_array_del_null( $arr_input['startkm'] ) ) ){
                return hello_error('请设置起始公里数');
            }
            if( empty( hi_array_del_null( $arr_input['overkm'] ) ) ){
                return hello_error('请设置结束公里数');
            }
            if( empty( hi_array_del_null( $arr_input['pricekm'] ) ) ){
                return hello_error('请设置价格');
            }
            foreach ( $arr_input['startkm'] as $key => $vo ){
                if( $vo > $arr_input['overkm'][$key] ){
                    return hello_error('起始公里数不能大于结束公里数');
                }
            }
        }
        return $arr_input;
    }



    /**
     *  获取指定的数据
     *  hinq 2020 4 22
     *
     **/
    public function get_one( int $id ){
        try{
            if( empty( $id ) ) {
                return hello_error( '参数错误');
            }
            $arr_option['with'] = ['extend'=>function($query){
                $query->select('id','link_id','startkm','overkm','price');
            }];
            $arr_list = RoadRescueConfigRepository::get_one( (int) $id , (array) $arr_option );
            if( empty( $arr_list->first() ) ){
                return hello_success( 'ok' , []);
            }
            return hello_success( 'ok' , $arr_list->toarray() );
        }catch ( \Exception $exception ){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  更新指定数据
     *  hinq 2020 4 22
     *
     **/
    public function update( array $arr_input ){
        try{
            //验证数据有效性
            $temp = self::check_data( (array) $arr_input );

            $data['type'] = $temp['type'];
            $data['pid'] = $temp['pid'];
            if( $temp['type'] == 1 ){   //按次数收费
                $data['price'] = $temp['price'];
            }
            //先删除extend中的信息
            RoadRescueConfigExtendRepository::delete_where_one( (array) ['link_id' => $temp['id']] );

            if( $temp['type'] == 2 ){   //按公里数收费
                $temp_extend['link_id'] = $temp['id'];
                foreach ($arr_input['startkm'] as $key => $vo) {
                    $temp_extend['startkm'] = $vo;      //起始公里数
                    $temp_extend['overkm'] = $arr_input['overkm'][$key];  //结束公里数
                    $temp_extend['price'] = $arr_input['pricekm'][$key];  //收费金额
                    $res = RoadRescueConfigExtendRepository::add_one((array)$temp_extend);
                }
            }
            $edit_data['id'] = $temp['id'];
            $edit_data['type'] = $temp['type'];
            $edit_data['price'] = $temp['price'];
            $res = RoadRescueConfigRepository::edit_one( (array) $edit_data );
            return hello_success('OK');
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }



    /**
     *  获取所有的订单列表
     *  hinq 2020 4 28
     **/
    public function order_list( array $arr_search ){
        try{
            $shop_id = shop_shop_id();
            $arr_option['where'] = ['shop_id'=>$shop_id];
            $arr_option['order'] = ['key'=>'created_at','value'=>'desc'];
            $arr_list = RoadRescueOrderRepository::get_list( (array) $arr_search , (array) $arr_option );

            //获取退款原因列表cancel_reason
            $arr_option2['where'] = ['type'=>3 , 'status'=>1];
            $arr_option2['first'] = ['id','reason'];
            $refubd_list = CancelReasonRepository::get_all( (array) $arr_option2 );   //道路救援退款的原因列表
            $temp = [];
            foreach ( $refubd_list as $key => $vo ){
                $temp[$vo['id']] = $vo['reason'];
            }
            $type_list = self::type_list(); //服务类型列表
            $arr_search['type_list'] = $type_list;
            $arr_list->appends($arr_search);//添加链接参数
            $arr_list = list_page_data($arr_list, $arr_search);
            foreach ( $arr_list['data'] as $key=>&$vo ){
                $vo['pid_msg'] = $type_list[ $vo['pid'] ];      //服务类型说明
                $vo['refubd_msg'] = $temp[ $vo['refund_id'] ];      //退款信息说明
                $vo['refund_time'] = date( 'Y-m-d H:i:s' , $vo['refund_time'] );  //退款时间
            }
            return hello_success('成功', $arr_list);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  获取订单想详细
     *  hinq 2020 4 29
     *
     **/
    public function order_detail( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            $arr_option['with'] = ['apprise'=>function( $query ){
                $query->select('id','order_id','score','content','images');
            },'user'=>function( $query ){
                $query->select('id','nickname','head_img');
            }];
            $arr_list = RoadRescueOrderRepository::get_one( (int) $nId , (array) $arr_option );
            if( empty( $arr_list->first()  ) ){
                return hello_error('ok',[]);
            }
            $arr_list = $arr_list->toarray();
            $arr_list['apprise']['images'] = explode(',' , $arr_list['apprise']['images'] );

            $type_list = self::type_list();
            $arr_list['pid_msg'] = $type_list[$arr_list['pid']];

            //获取退款原因列表cancel_reason
            $arr_option2['where'] = ['type'=>3 , 'status'=>1];
            $arr_option2['first'] = ['id','reason'];
            $refubd_list = CancelReasonRepository::get_all( (array) $arr_option2 );
            $temp = [];
            foreach ( $refubd_list as $key => $vo ){
                $temp[$vo['id']] = $vo['reason'];
            }
            $arr_list['refubd_msg'] = $temp[ $arr_list['refund_id'] ];
            $arr_list['deduct_price'] = empty( $temp['deduct_price'] ) ? '0.00' : $temp['deduct_price'];
            $arr_list['refund_price'] = empty( $temp['refund_price'] ) ? '0.00' : $temp['refund_price'];

            return hello_success('ok',$arr_list);
        }catch (\Exception $exception){
            return  hello_error( $exception->getMessage() );
        }
    }

    /**
     *  审核退款信息
     *  hinq 2020 4 30
     *  id   订单id
     *  type 处理类型  21 ：驳回申请   22：通过退款
     *  refund_msg   审核原因
     *
     *  12 17 25 30 33  5 9
     *  2 6 15 23 25    1 6
     *
     **/
    public function order_shenhe( array $arr_input ){
        try{
            //获取订单信息
            $arr_option['field'] = ['id','pay_status','status','order_sn','refund_no','user_id','shop_id','pid'];
            $info = RoadRescueOrderRepository::get_one( (int) $arr_input['id'] , $arr_option );
            if( empty( $info->first() ) ){
                return hello_error('参数错误');
            }
            $info = $info->toarray();
            if( $info['pay_status']['id'] != 1 ){
                return hello_error('订单未支付');
            }
            if( $info['status']['id'] != 2 ){
                return hello_error('该订单未申请退款');
            }
            if( $info['status']['id'] == 22 ){
                return hello_error('已成功退款，请勿重复退款');
            }
            if( $arr_input['type'] == 22 ){   //通过申请退款
                //将审核信息保存到数据表中
                $temp['id'] = $arr_input['id'];
                $temp['refund_msg'] = $arr_input['refund_msg'];
                $res = RoadRescueOrderRepository::edit_one( (array) $temp );
                \HiCommon\Service\PayRefundService::api_online_pay_refund( $info['order_sn'] , $info['refund_no'] );
                return hello_success('ok');
            }else{   //驳回退款申请
                $temp['id'] = $arr_input['id'];
                $temp['status'] = 21;
                $temp['refund_msg'] = $arr_input['refund_msg'];
                $temp['refund_time_success'] = time();
                $res = RoadRescueOrderRepository::edit_one( (array) $temp );
                if( !$res ){
                    return hello_error('退款申请驳回失败');
                }

                $arr_list = road_rescue_server_type();
                $service_pid_image = '';
                $service_pid_name = '';
                foreach ( $arr_list as $key => $vo ){
                    if( $vo['id'] == $info['pid'] ){
                        $service_pid_image = $vo['image'];
                        $service_pid_name = $vo['name'];
                    }
                }
                $temp['type'] = 33;  //【订单消息】退款成功
                $temp['price'] = 0;
                $temp['service_pid'] = $info['pid'];
                $temp['shop_id'] = $info['shop_id'];
                $temp['order_status'] = 22;
                $temp['order_type'] = 4;

                $arr_jpush['extras']['pid'] = 3;
                add_message( $service_pid_image ,'退款失败','您的道路救援订单【'.$service_pid_name.'】退款失败；说明：【'.$arr_input['refund_msg'].'】' , $info['user_id'] , 3 , $info['id'] , $arr_jpush , $temp );
                return hello_success('ok');
            }
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }


}